package com.weishi.project.api.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.config.ThreadPoolConfig;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.api.controller.selection.WeekPlanSelection;
import com.weishi.project.api.controller.thread.WeekPlanRunnable;
import com.weishi.project.api.ret.ChannelIdVO;
import com.weishi.project.api.service.ApiWeekPlanService;
import com.weishi.project.api.vo.HeartRateCountVo;
import com.weishi.project.api.vo.WeekDetailsVo;
import com.weishi.project.api.vo.appvo.GetWaterDataVO;
import com.weishi.project.api.vo.appvo.GetWaterListVO;
import com.weishi.project.api.vo.appvo.SubmitResultsDTO;
import com.weishi.project.api.vo.appvo.WeeklyPlanListVO;
import com.weishi.project.speedometer.vo.CurrentShipSpeedVo;
import com.weishi.project.speedometer.vo.RealTimeDataVo;
import com.weishi.project.system.service.ISysDictDataService;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * ApiWeekPlanController 接口实现类
 */
@Service
public class ApiWeekPlanServiceImpl implements ApiWeekPlanService {

    /**
     * 训练航道接口
     */
    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * 训练成绩
     */
    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    /**
     * 心率表 接口
     */
    @Autowired
    private IHeartRateRecordService heartRateRecordService;

    @Autowired
    private IHeartRateService heartRateService;

    /**
     * 船速仪历史数据接口
     */
    @Autowired
    private IShipSpeedRecordService shipSpeedRecordService;

    /**
     * 船速仪实时数据接口
     */
    @Autowired
    private IShipSpeedRecordLogService shipSpeedRecordLogService;

    /**
     * 注入线程池
     */
    @Resource
    private ThreadPoolConfig threadPoolConfig;

    /**
     * redis 数据库
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 增删改线程
     */
    @Autowired
    private WeekPlanRunnable weekPlanRunnable;

    /**
     * 心率计次数据
     */
    @Autowired
    private IHeartRateCountService heartRateCountService;

    /**
     * 测功仪接口
     */
    @Autowired
    private IDynamometerService dynamometerService;

    /**
     * 测功仪分段数据 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;

    @Autowired
    private ITrainingGroupService trainingGroupService;

    /**
     * 训练课 接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    /**
     * 训练周 接口
     */
    @Autowired
    private ITrainingWeekService trainingWeekService;

    /**
     * 字典值 接口
     */
    @Autowired
    private ISysDictDataService dictDataService;





    /**
     * 教练员端 -- 水上(陆上)训练——新增训练小组航道
     */
    @Override
    public AjaxResult addChannel(JSONObject jsonObject) {

        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("trainingGroupChannels");
        List<TrainingGroupChannel> channelList = JSON.parseArray(jsonArray.toString(), TrainingGroupChannel.class);
        if (channelList.size() > 0) {
            channelList.forEach(p -> {

                p.setCtime(new Date());
                if (Integer.parseInt(jsonObject.get("trainingMode").toString()) == 0) {
                    p.setRowingClassHour(0.0);
                } else if (Integer.parseInt(jsonObject.get("trainingMode").toString()) == 1) {
                    p.setRowingKilometers(0);
                }
                if (p.getId() == -1) {
                    p.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                    p.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                    trainingGroupChannelService.save(p);
                } else {
                    p.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                    p.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                    trainingGroupChannelService.updateById(p);
                }

            });


            // 把组id 放进去

            // 把新增成功的数据返回给前端
            List<ChannelIdVO> channelIdVOList = new ArrayList<>();
            List<TrainingGroupChannel> trainingGroupChannel2 = trainingGroupChannelService.list(Wrappers.<TrainingGroupChannel>lambdaQuery().eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString())));
            if (trainingGroupChannel2.size() > 0) {
                trainingGroupChannel2.forEach(pp -> {
                    ChannelIdVO channelIdVO = new ChannelIdVO();
                    StringUtils.copyProperties(pp, channelIdVO);
                    channelIdVOList.add(channelIdVO);
                });
            }

            // 返回数据
            return AjaxResult.success(channelIdVOList);


        }

        return AjaxResult.success();
    }


    /**
     * 教练员端 -- 保存人艇选择 -- 到航道
     */
    @Override
    public AjaxResult addHumanBoat(JSONObject jsonObject) {
        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("personList");
        List<TrainingAchievement> trainingAchievementList = JSON.parseArray(jsonArray.toString(), TrainingAchievement.class);

        // 保存或者修改数据
        // 先查询成绩表的id , 然后就把之前的人删掉
        List<TrainingAchievement> trainingAchievementList1 = trainingAchievementService.list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString())));
        if (trainingAchievementList1.size() > 0) {
            trainingAchievementList1.forEach(pp -> {
                trainingAchievementService.removeById(pp.getId());
            });
        }

        // 删除结束

        if (trainingAchievementList.size() > 0) {
            trainingAchievementList.forEach(p -> {

                // 删除成功时候，就重新，新增数据
                p.setCtime(new Date());
                p.setWeekId(Integer.parseInt(jsonObject.get("weekId").toString()));
                p.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                p.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                p.setChannelId(Integer.parseInt(jsonObject.get("channelId").toString()));
                trainingAchievementService.save(p);

                // 根据 航道 id 更新 boatType 值
                TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
                trainingGroupChannel.setBoatType(jsonObject.get("boatType").toString());
                trainingGroupChannel.setId(Integer.parseInt(jsonObject.get("channelId").toString()));
                trainingGroupChannel.setChannelInfoStr(jsonObject.get("channelInfoStr").toString());
                trainingGroupChannelService.updateById(trainingGroupChannel);

            });
        }
        return AjaxResult.success();
    }


    /**
     * 教练员端 -- 复制上一组数据
     */
    @Override
    @Transactional
    public AjaxResult copyGoUpGroup(JSONObject jsonObject) {
        /**
         * 首先根据传来的 上一组 id 查询所有航道信息，然后保存航道，保存的组 id 为下一组的 组 id
         * 2，然后再根据上一组 id 查询成绩数据，然后信息，保存的 组id 为下一组的 id
         */
        // 先删掉之前的航道
        List<TrainingGroupChannel> groupChannelList = trainingGroupChannelService.list(Wrappers.<TrainingGroupChannel>lambdaQuery().eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("lowerGroupId").toString())));
        if (groupChannelList.size() > 0) {
            groupChannelList.forEach(p -> {
                trainingGroupChannelService.removeById(p.getId());
            });
        }

        // 先删掉之前的成绩
        List<TrainingAchievement> achievementList = trainingAchievementService.list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getGroupId, Integer.parseInt(jsonObject.get("lowerGroupId").toString())));
        if (achievementList.size() > 0) {
            achievementList.forEach(p -> {
                trainingAchievementService.removeById(p.getId());
            });
        }

        // 保存航道数据
        List<TrainingGroupChannel> trainingGroupChannelList = trainingGroupChannelService.list(Wrappers.<TrainingGroupChannel>lambdaQuery().eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("upperGroupId").toString())));
        if (trainingGroupChannelList.size() > 0) {
            trainingGroupChannelList.forEach(p -> {
                Integer channelId = p.getId();
                p.setGroupId(Integer.parseInt(jsonObject.get("lowerGroupId").toString()));
                p.setAchievement("");
                p.setSegmentedTiming("");
                p.setAchievementMs(0);
                trainingGroupChannelService.save(p);

                // 保存成绩表数据
                List<TrainingAchievement> trainingAchievementList = trainingAchievementService.list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getChannelId, channelId));
                if (trainingAchievementList.size() > 0) {
                    trainingAchievementList.forEach(pp -> {
                        pp.setGroupId(Integer.parseInt(jsonObject.get("lowerGroupId").toString()));
                        pp.setChannelId(p.getId());
                        trainingAchievementService.save(pp);
                    });
                }
            });
        }
        return AjaxResult.success();
    }


    // 求分段平均速度值，和平均浆频
    public Map shipSpeedAndPropellerFrequency(Integer channelId){
        Map map = new HashMap();
        // 求平均速度
        double shipSpeed = 0.0;
        // 求平均浆频
        Integer propellerFrequency = 0;
        List<HeartRateCount> heartRateCountList = heartRateCountService
                .list(Wrappers.<HeartRateCount>lambdaQuery()
                        .eq(HeartRateCount::getChannelId , channelId));
        for (int j = 0; j<heartRateCountList.size(); j++){
            // 平均速度
            if(StringUtils.isNotNull(heartRateCountList.get(j).getShipSpeed()) && heartRateCountList.get(j).getShipSpeed() > 0.0){
                shipSpeed += heartRateCountList.get(j).getShipSpeed();
            }
            // 平均浆频
            if(StringUtils.isNotNull(heartRateCountList.get(j).getPropellerFrequency()) && !"".equals(heartRateCountList.get(j).getPropellerFrequency())){
                propellerFrequency += Integer.parseInt(heartRateCountList.get(j).getPropellerFrequency());
            }
        }
        // 平均速度
        if(shipSpeed > 0.0){
            map.put("shipSpeed" , String.format("%.2f", shipSpeed / heartRateCountList.size()));
        }else{
            map.put("shipSpeed" , 0.0);
        }

        // 平均浆频
        if(propellerFrequency > 0){
            map.put("propellerFrequency" , propellerFrequency / heartRateCountList.size());
        }else{
            map.put("propellerFrequency" , 0);
        }
        return map;
    }

    /**
     * 教练员端 -- 查询小组的成绩
     */
    @Override
    public AjaxResult getGroupPerformance(JSONObject jsonObject) {
        // 根据 trainingMode 判断
        if (Integer.parseInt(jsonObject.get("trainingMode").toString()) == 0) {
            // 1，先查询船的分组
            List<TrainingGroupChannel> groupList = trainingGroupChannelService
                    .list(Wrappers.<TrainingGroupChannel>lambdaQuery()
                            .eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                            .isNotNull(TrainingGroupChannel::getAchievement)
                            .groupBy(TrainingGroupChannel::getBoatType));
            List<TrainingGroupChannel> trainingGroupChannelList3 = new ArrayList<>();
            if (groupList.size() > 0) {
                groupList.forEach(g -> {
                    if (!g.getAchievement().equals("")) {
                        List<TrainingGroupChannel> trainingGroupChannelList = trainingGroupChannelService
                                .list(Wrappers.<TrainingGroupChannel>lambdaQuery()
                                        .eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                                        .eq(TrainingGroupChannel::getBoatType, g.getBoatType())
                                        .isNotNull(TrainingGroupChannel::getAchievement)
                                        .orderByAsc(TrainingGroupChannel::getAchievement));

                        if (trainingGroupChannelList.size() > 0) {
                            trainingGroupChannelList.forEach(p -> {
//                            List<TrainingGroupChannel> trainingChannelList = trainingAchievementService.list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getGroupId , Integer.parseInt(jsonObject.get("groupId").toString())));
//                            p.setPerson();
//                            p.setId();
//                            trainingGroupChannelList3.add(p);
                                Integer channelId = p.getId();
                                List<TrainingAchievement> personList = trainingAchievementService
                                        .list(Wrappers.<TrainingAchievement>lambdaQuery()
                                                .eq(TrainingAchievement::getChannelId, channelId));
                                if (null != personList && personList.size() > 0) {
                                    Integer achievementId = personList.get(0).getId();
                                    p.setChannelId(channelId);
                                    p.setId(achievementId);
                                    // 查询水上分段数据
                                    for (int i = 0; i<personList.size(); i++){
                                        // 求平均速度
                                        p.setShipSpeed(Double.parseDouble(this.shipSpeedAndPropellerFrequency(personList.get(i).getChannelId()).get("shipSpeed").toString()));
                                        // 求平均浆频
                                        p.setPropellerFrequency(this.shipSpeedAndPropellerFrequency(personList.get(i).getChannelId()).get("propellerFrequency").toString());
                                    }
                                    trainingGroupChannelList3.add(p);
                                }
                            });
                        }
                    }
                });
            }

            return AjaxResult.success(trainingGroupChannelList3);
        } else {
            // 1，先查询船的分组
            List<TrainingGroupChannel> groupList = trainingGroupChannelService
                    .list(Wrappers.<TrainingGroupChannel>lambdaQuery()
                            .eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                            .isNotNull(TrainingGroupChannel::getAchievement)
                            .groupBy(TrainingGroupChannel::getBoatType));
            List<TrainingGroupChannel> trainingGroupChannelList3 = new ArrayList<>();
            if (groupList.size() > 0) {
                groupList.forEach(g -> {
                    if (!g.getAchievement().equals("")) {
                        List<TrainingGroupChannel> trainingGroupChannelList = trainingGroupChannelService
                                .list(Wrappers.<TrainingGroupChannel>lambdaQuery()
                                        .eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                                        .eq(TrainingGroupChannel::getBoatType, g.getBoatType())
                                        .isNotNull(TrainingGroupChannel::getAchievement)
                                        .orderByDesc(TrainingGroupChannel::getAchievement));
                        if (trainingGroupChannelList.size() > 0) {
                            trainingGroupChannelList.forEach(p -> {
                                //p.setPerson(trainingAchievementService.list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getGroupId , Integer.parseInt(jsonObject.get("groupId").toString()))));
                                //trainingGroupChannelList3.add(p);

                                Integer channelId = p.getId();
                                List<TrainingAchievement> personList = trainingAchievementService
                                        .list(Wrappers.<TrainingAchievement>lambdaQuery()
                                                .eq(TrainingAchievement::getChannelId, channelId));
                                if (null != personList && personList.size() > 0) {
                                    Integer achievementId = personList.get(0).getId();
                                    p.setChannelId(channelId);
                                    p.setId(achievementId);
                                    p.setSpeed(p.getAverageSpeed()!=null ? Double.parseDouble(p.getAverageSpeed()):0);
                                    // 查询水上分段数据
                                    for (int i = 0; i<personList.size(); i++){
                                        // 求平均速度
                                        p.setShipSpeed(Double.parseDouble(this.shipSpeedAndPropellerFrequency(personList.get(i).getChannelId()).get("shipSpeed").toString()));
                                        // 求平均浆频
                                        p.setPropellerFrequency(this.shipSpeedAndPropellerFrequency(personList.get(i).getChannelId()).get("propellerFrequency").toString());
                                    }
                                    trainingGroupChannelList3.add(p);
                                }

                            });
                        }
                    }
                });
            }

            return AjaxResult.success(trainingGroupChannelList3);
        }
    }


    /**
     * 教练员端 -- 根据航道 id 查询航道的人
     */
    @Override
    public AjaxResult getChannelIdList(JSONObject jsonObject) {
        List<TrainingAchievement> trainingAchievementList = trainingAchievementService.list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getChannelId, Integer.parseInt(jsonObject.get("id").toString())).orderByAsc(TrainingAchievement::getPosition));
        if (trainingAchievementList.size() > 0) {
            trainingAchievementList.forEach(p -> {
                p.setBoatType(trainingGroupChannelService.getById(Integer.parseInt(jsonObject.get("id").toString())).getBoatType());
            });
        }
        return AjaxResult.success(trainingAchievementList);
    }


    /**
     * 教练员端 -- 根据组 id 查询所有的航道
     */
    @Override
    public AjaxResult getGroupChannelList(JSONObject jsonObject) {
        return AjaxResult.success(trainingGroupChannelService.list(Wrappers.<TrainingGroupChannel>lambdaQuery().eq(TrainingGroupChannel::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))));
    }


    /**
     * 教练员端 -- 根据航道id，运动员 id，分组 id，查询 20 条心率
     */
    @Override
    public AjaxResult getHeartRateList(JSONObject jsonObject) {
        Integer index = 20;
        List<HeartRate> heartRateList = heartRateService.list(Wrappers.<HeartRate>lambdaQuery().eq(HeartRate::getSportsmanId, Integer.parseInt(jsonObject.get("sportsmanId").toString())).eq(HeartRate::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString())).eq(HeartRate::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString())));
        if (heartRateList.size() <= 20) {
            return AjaxResult.success(heartRateList);
        } else {
            List<HeartRate> heartRateList2 = new ArrayList<>();
            Integer size = heartRateList.size();
            for (int i = 0; i < heartRateList.size(); i++) {
                size--;
                if (index > 0) {
                    heartRateList2.add(heartRateList.get(size));
                    index--;
                }
            }
            return AjaxResult.success(heartRateList2);
        }
    }


    /**
     * 教练员端 -- 根据航道id，运动员 id，分组 id，查询 20 条 船速仪
     */
    @Override
    public AjaxResult getShipSpeedList(JSONObject jsonObject) {
        int channelId = Integer.parseInt(jsonObject.get("channelId").toString());
        List<RealTimeDataVo> realTimeDataVos = shipSpeedRecordLogService.selectDataListByChannelId(channelId);
        for(RealTimeDataVo vo : realTimeDataVos){
            String realTime = vo.getRealTime();
            try {
                String[] aa = realTime.split("\\.");
                String h = aa[0].substring(0,2);
                String m = aa[0].substring(2,4);
                String s = aa[0].substring(4);
                realTime = h+":"+m+":"+s;
            } catch (Exception e) {
                e.printStackTrace();
            }
            vo.setRealTime(realTime);
        }
        return AjaxResult.success(realTimeDataVos);
    }


    /**
     * 教练员端 -- 查询水上专项实时数据 1，船速 2，浆频 3，心率
     */
    @Override
    public AjaxResult getWaterList(JSONObject jsonObject) {
        // 封装的返回值
        GetWaterListVO getWaterListVO = null;
        try {
            getWaterListVO = new GetWaterListVO();

            // 查询船速 和 浆频
            ShipSpeedRecord params = new ShipSpeedRecord();
            ShipSpeedRecord shipSpeedRecordRet = new ShipSpeedRecord();
            if(jsonObject.get("shipSpeedId")!=null && jsonObject.get("channelId")!=null){
                params.setChannelId(Integer.parseInt(jsonObject.get("channelId").toString()));
                params.setShipSpeedId(jsonObject.get("shipSpeedId").toString());
                shipSpeedRecordRet = shipSpeedRecordService.selectShipSpeedRecord(params);
            }


            // 查询心率
            Map<String, Object> heartRateParams = new HashMap<>();
            heartRateParams.put("sportsmanId", Integer.parseInt(jsonObject.get("sportsmanId").toString()));
            heartRateParams.put("channelId", Integer.parseInt(jsonObject.get("channelId").toString()));
            List<HeartRateRecord> heartRateRecordList = heartRateRecordService.selectByMap(heartRateParams);
            JSONArray array = new JSONArray();
            for (HeartRateRecord heartRateRecord : heartRateRecordList) {
                if(StringUtils.isNotNull(heartRateRecord.getJsondata())){
                    try {
                        JSONArray arrayTemp = JSONUtil.parseArray(heartRateRecord.getJsondata());
                        array.addAll(arrayTemp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            // 获取心率曲线
            getWaterListVO.setHeartRateList(array);
            // 获取船速曲线
            if (shipSpeedRecordRet != null && StringUtils.isNotEmpty(shipSpeedRecordRet.getDatajson())) {
                getWaterListVO.setRealTimeDataVoList(JSONUtil.parseArray(shipSpeedRecordRet.getDatajson()));
            }
            // 获取桨频曲线
            if (shipSpeedRecordRet != null && StringUtils.isNotEmpty(shipSpeedRecordRet.getDatajsonPropellerFrequency())) {
                getWaterListVO.setPropellerFrequencyList(JSONUtil.parseArray(shipSpeedRecordRet.getDatajsonPropellerFrequency()));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        // 返回查询的数据
        return AjaxResult.success(getWaterListVO);
    }


    /**
     * 教练员端 -- 提交成绩
     */
    @Override
    public AjaxResult submitResults(JSONObject jsonObject) {
        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("achievementList");
        List<SubmitResultsDTO> channelList = JSON.parseArray(jsonArray.toString(), SubmitResultsDTO.class);
        if (channelList.size() > 0) {
            channelList.forEach(p -> {
                if (p.getChannnelList().size() > 0) {
                    p.getChannnelList().forEach(pp -> {
                        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelService.getById(pp.getChannelId());
                        trainingGroupChannel.getTrainingMode();
                        StringUtils.copyProperties(pp, trainingGroupChannel);

                        /*if(trainingGroupChannel.getTrainingMode()!=null && trainingGroupChannel.getTrainingMode()==1){
                            trainingGroupChannel.setAchievement(achievement);
                        }*/
                        trainingGroupChannel.setId(pp.getChannelId());
                        trainingGroupChannelService.updateById(trainingGroupChannel);
                        //同步完成公里数
                        //获取小组实际公里数(第一批次，第一航道的实际划行数) [公里数维度，时间维度暂时忽略]
                        if (trainingGroupChannel.getChannelName().equals("0") && trainingGroupChannel.getBatch() == 0) {
                            trainingGroupChannel = trainingGroupChannelService.getById(trainingGroupChannel.getId());
                            TrainingGroup trainingGroup = trainingGroupService.getById(trainingGroupChannel.getGroupId());
                            trainingGroup.setKilometer(trainingGroupChannel.getRowingKilometers());
                            trainingGroupService.updateById(trainingGroup);
                            //异步汇总训练项目数据
                            trainingDayService.aggregateData(trainingGroup.getTrainingDayId());
                        }
                    });
                }
            });
        }

        return AjaxResult.success();
    }


    /**
     * 教练员端 -- 点击计次按钮
     */
    @Override
    public AjaxResult countTimes(JSONObject jsonObject) {
        redisTemplate.boundListOps("ApiWeekPlanServiceImpl_countTimes").leftPush(jsonObject);
        WeekPlanSelection.setValue("ApiWeekPlanServiceImpl_countTimes");
        threadPoolConfig.threadPoolTaskExecutor().execute(weekPlanRunnable);
        return AjaxResult.success();
    }


    /**
     * 教练员端 -- 查询计次
     */
    @Override
    public List<HeartRateCountVo> getCountTimes(JSONObject jsonObject) {
        List<HeartRateCountVo> heartRateCountList = heartRateCountService.qryCountBySportsman(Integer.parseInt(jsonObject.get("channelId").toString()), Integer.parseInt(jsonObject.get("sportsmanId").toString()));
        return heartRateCountList;
    }


    /**
     * 教练员端 -- 测功仪数据 --- 查询分段成绩
     */
    @Override
    public AjaxResult getSubsection(JSONObject jsonObject) {
        List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                        .eq(DynamometerSubsection::getSportsmanId, Integer.parseInt(jsonObject.get("sportsmanId").toString()))
                        .eq(DynamometerSubsection::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                        .orderByAsc(DynamometerSubsection::getSegmentNumber));

        List<DynamometerSubsection> dynamometerSubsectionList2 = new ArrayList<>();
        if (dynamometerSubsectionList.size() > 0) {
            if (dynamometerSubsectionList.size() == 1) {
                double mileage = dynamometerSubsectionList.get(0).getMileage();
                Long lengthTime = StringUtils.turnSecond(dynamometerSubsectionList.get(0).getLengthTime());
                Double mileages = StringUtils.numberDigits(mileage / (lengthTime / 1000) , 2);
                dynamometerSubsectionList.get(0).setSpeed(mileages);
                dynamometerSubsectionList2.add(dynamometerSubsectionList.get(0));
                return AjaxResult.success(dynamometerSubsectionList2);
            } else {

                // 总数据
                int size = dynamometerSubsectionList.size();
                // 起始数
                int index = 0;
                for (int i = 0; i < dynamometerSubsectionList.size(); i++) {
                    //  trainingMode =  0 减时间  1 减距离
                    if (dynamometerSubsectionList.get(i).getTrainingMode() == 0) {
                        if (index < size) {
                            DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                            StringUtils.copyProperties(dynamometerSubsectionList.get(i), dynamometerSubsection);
                            if (index == 0) {
                                dynamometerSubsectionList2.add(dynamometerSubsection);
                            } else {
                                Long lengthTime = StringUtils.turnSecond(dynamometerSubsectionList.get(i).getLengthTime());
                                Long lengthTime2 = StringUtils.turnSecond(dynamometerSubsectionList.get(index - 1).getLengthTime());
                                Long lengthTime3 = lengthTime - lengthTime2;
                                //double mileage = dynamometerSubsectionList.get(i).getMileage();
                                //double mileage2 = dynamometerSubsectionList.get(index - 1).getMileage();
                                //double mileage3 = mileage - mileage2;
                                //Double mileages = StringUtils.numberDigits(mileage3 / (lengthTime3 / 1000) , 2);
                                //dynamometerSubsection.setSpeed(mileages);
                                dynamometerSubsection.setLengthTime(StringUtils.millisecondRotationTime(lengthTime3));
                                dynamometerSubsectionList2.add(dynamometerSubsection);
                            }
                            index++;
                        }

                    } else {

                        if (index < size) {
                            DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                            StringUtils.copyProperties(dynamometerSubsectionList.get(i), dynamometerSubsection);
                            if (index == 0) {
                                dynamometerSubsectionList2.add(dynamometerSubsection);
                            } else {
                                double mileage = dynamometerSubsectionList.get(i).getMileage();
                                double mileage2 = dynamometerSubsectionList.get(index - 1).getMileage();
                                double mileage3 = mileage - mileage2;
                                //Double mileages = StringUtils.numberDigits(mileage3 / (dynamometerSubsection.getSpeed() / 1000) , 2);
                                //dynamometerSubsection.setSpeed(mileages);
                                // 设置保留 1 位小数
                                dynamometerSubsection.setMileage(StringUtils.numberDigits(mileage3 , 1));
                                dynamometerSubsectionList2.add(dynamometerSubsection);
                            }
                            index++;
                        }

                    }


                }
                return AjaxResult.success(dynamometerSubsectionList2);
            }

        }
        return AjaxResult.success();
    }



    /**
     * 教练员端 -- 本周数据查询列表 -- 训练计划总表
     */
    @Override
    public AjaxResult getWeeklyPlanListVO(JSONObject jsonObject) {
        List<WeeklyPlanListVO> weeklyPlanListVOList = new ArrayList<>();
        List<WeekDetailsVo> weekList = trainingWeekService.getWeekDetails(Integer.parseInt(jsonObject.get("weekId").toString()));
        // 查询字典值 四时
        //List<TypeValueVO> dictDataList = dictDataService.getTypeValue("four_seasons");
                if(weekList.size() > 0)weekList.forEach( p-> {
                    WeeklyPlanListVO weeklyPlanListVO = new WeeklyPlanListVO();
                    List<WeeklyPlanListVO.WeeklyPlan> weeklyPlanList = new ArrayList<>();
                        // 训练日期
                        weeklyPlanListVO.setDay(p.getDay());
                        // 训练数据列表
                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String nowTime = df.format(p.getDay());
                        List<TrainingDay> beforedawnList = trainingDayService
                                .list(Wrappers.<TrainingDay>lambdaQuery()
                                        .eq(TrainingDay::getDay , nowTime)
                                        .orderByAsc(TrainingDay::getStartTime));
                        if(beforedawnList.size() > 0){
                            beforedawnList.forEach( b-> {
                                WeeklyPlanListVO.WeeklyPlan weeklyPlan = new WeeklyPlanListVO.WeeklyPlan();
                                StringUtils.copyProperties(b , weeklyPlan);
                                weeklyPlan.setClassHour(b.getRealClassHour()); // 计算时长
                                weeklyPlanList.add(weeklyPlan);
                                weeklyPlanListVO.setWeeklyPlanList(weeklyPlanList);
                            });
                        }
                    weeklyPlanListVOList.add(weeklyPlanListVO);
                    });
        return AjaxResult.success(Optional.ofNullable(weeklyPlanListVOList));
    }

    /**
     * 教练员端 -- 查询训练课质量
     */
    @Override
    public AjaxResult getTrainingCourseQuality() {
        return AjaxResult.success(Optional.ofNullable(dictDataService
                        .getTypeValue("training_course_quality")));
    }

    /**
     * 教练员端 -- 根据课程 id 修改课程质量
     */
    @Transactional
    @Override
    public AjaxResult updateQualityById(JSONObject jsonObject) {
        // 查询课程详情
        TrainingDay training = trainingDayService.getById(Integer.parseInt(jsonObject.get("id").toString()));
        TrainingDay trainingDay = new TrainingDay();
        StringUtils.copyProperties(training , trainingDay);
        trainingDay.setQuality(jsonObject.get("quality").toString());
        trainingDay.setId(Integer.parseInt(jsonObject.get("id").toString()));
        trainingDayService.updateById(trainingDay);
        return AjaxResult.success();
    }

    @Override
    public List<GetWaterDataVO> getWaterDataList(String shipSpeedId, int channelId, int sportsmanId) {
        List<GetWaterDataVO> retList = new ArrayList<>();
        Map<String,GetWaterDataVO> temp = new HashMap<>();
        try {
            ShipSpeedRecord shipSpeedRecordRet = new ShipSpeedRecord();

            if(StringUtils.isNotEmpty(shipSpeedId)){
                // 查询船速 和 浆频
                ShipSpeedRecord params = new ShipSpeedRecord();
                params.setChannelId(channelId);
                params.setShipSpeedId(shipSpeedId);
                shipSpeedRecordRet = shipSpeedRecordService.selectShipSpeedRecord(params);
            }

            // 查询心率
            Map<String, Object> heartRateParams = new HashMap<>();
            heartRateParams.put("sportsmanId", sportsmanId);
            heartRateParams.put("channelId", channelId);
            List<HeartRateRecord> heartRateRecordList = heartRateRecordService.selectByMap(heartRateParams);
            JSONArray array = new JSONArray();
            for (HeartRateRecord heartRateRecord : heartRateRecordList) {
                if(StringUtils.isNotNull(heartRateRecord.getJsondata())){
                    try {
                        JSONArray arrayTemp = JSONUtil.parseArray(heartRateRecord.getJsondata());
                        array.addAll(arrayTemp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            // 获取心率曲线
            for(Object json : array){
                Map<String,Object> map = (Map<String, Object>) json;
                GetWaterDataVO vo = new GetWaterDataVO();
                vo.setHr((int)map.get("hr"));
                vo.setTime(map.get("time").toString());
                temp.put(DateUtils.formatString_HHmmss(map.get("time").toString()),vo);
            }
            // 获取船速曲线
            if (shipSpeedRecordRet != null && StringUtils.isNotEmpty(shipSpeedRecordRet.getDatajson())) {
                JSONArray shipSpeedRecords = JSONUtil.parseArray(shipSpeedRecordRet.getDatajson());
                for(Object json : shipSpeedRecords){
                    Map<String,Object> map = (Map<String, Object>) json;
                    GetWaterDataVO vo = temp.get(DateUtils.formatString_HHmmss(map.get("realTime").toString()));
                    if(vo==null){
                        vo = new GetWaterDataVO();
                        vo.setTime(map.get("realTime").toString());
                    }

                    vo.setDistance((double)map.get("distanceTotal"));
                    vo.setSpeed((double)map.get("distance"));
                    temp.put(DateUtils.formatString_HHmmss(map.get("realTime").toString()),vo);
                }
            }
            // 获取桨频曲线
            if (shipSpeedRecordRet != null && StringUtils.isNotEmpty(shipSpeedRecordRet.getDatajsonPropellerFrequency())) {
                JSONArray propellerFrequencys = JSONUtil.parseArray(shipSpeedRecordRet.getDatajsonPropellerFrequency());
                for(Object json : propellerFrequencys){
                    Map<String,Object> map = (Map<String, Object>) json;
                    GetWaterDataVO vo = temp.get(DateUtils.formatString_HHmmss(map.get("realTime").toString()));
                    if(vo==null){
                        vo = new GetWaterDataVO();
                        vo.setTime(map.get("realTime").toString());
                    }
                    vo.setPropellerFrequency((int)Math.round((double)map.get("averagePropeller")));
                    temp.put(DateUtils.formatString_HHmmss(map.get("realTime").toString()),vo);
                }
            }

            //三个曲线合并为一个曲线
            List<String> times = new ArrayList<>(temp.keySet());
            Collections.sort(times);

            GetWaterDataVO pre = temp.get(times.get(0));
            for(String key : times){
                GetWaterDataVO vo = temp.get(key);

                //处理桨频为0的点
                if(vo.getPropellerFrequency()==0){
                    vo.setPropellerFrequency(pre.getPropellerFrequency());
                }

                //处理心率为0的点
                if(vo.getHr()==0){
                    vo.setHr(pre.getHr());
                }
                //处理速度为0的点
                if(vo.getSpeed()==0){
                    vo.setSpeed(pre.getSpeed());
                    vo.setDistance(pre.getDistance());
                }
                pre = vo;
                retList.add(vo);
            }

            if(StringUtils.isNotEmpty(retList)){
                GetWaterDataVO vo = retList.get(0);//第一点的桨频设置为0；
                vo.setPropellerFrequency(0);
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        // 返回查询的数据
        return retList;
    }

    @Override
    public List<CurrentShipSpeedVo> selectRealTimeDataByChannelId(int channelId) {
        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelService.getById(channelId);
        List<CurrentShipSpeedVo> retList = new ArrayList<>();
        if(trainingGroupChannel!=null && trainingGroupChannel.getStime()!=null){
            Date startTime = trainingGroupChannel.getStime();
            ShipSpeedRecordLog params = new ShipSpeedRecordLog();
            params.setChannelId(channelId);
            List<ShipSpeedRecordLog> list = shipSpeedRecordLogService.selectShipSpeedRecordLogList(params);
            for(ShipSpeedRecordLog shipSpeedRecordLog : list){
                CurrentShipSpeedVo vo = new CurrentShipSpeedVo();
                vo.setRealTime(getRealTime(startTime,Long.parseLong(shipSpeedRecordLog.getTimp())));
                vo.setDistance(shipSpeedRecordLog.getDistance());
                vo.setPropellerFrequency(shipSpeedRecordLog.getPropellerFrequency());
                vo.setSpeed(shipSpeedRecordLog.getSpeed());
                retList.add(vo);
            }
        }
        return  retList;
    }

    private String getRealTime(Date startTime, long end) {
        long start = startTime.getTime();
        return DateUtils.getStringTime(end - start);
    }
}
